package org.ashleygwinnell.snahs.handlers;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.CharBuffer;

import org.ashleygwinnell.snahs.RequestHandler;

public abstract class GETRequestHandler extends RequestHandler
{
	private String requestedFilename;
	private String contentType;
	private boolean fileFound;
	
	private String sourceHost;
	private String sourcePort;
	
	private File file;
	
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	
	public void return200Response() throws IOException
	{
		this.getOutputStream().write("HTTP/1.1 200 OK\r\n".getBytes());
		this.getOutputStream().write(("Server: " + this.getServer().getName() + "\r\n").getBytes());
		this.getOutputStream().write("Accept-Ranges: bytes\r\n".getBytes());
		this.getOutputStream().write("Content-Length: 923874\r\n".getBytes());
		this.getOutputStream().write("Connection: close\r\n".getBytes());
		this.getOutputStream().write(("Content-Type: " + this.getContentType() + "\r\n\r\n").getBytes());
		
		FileReader reader = new FileReader(this.getFile());
		CharBuffer buffer = CharBuffer.allocate(3096);
		reader.read(buffer);
		for (int i = 0; i < buffer.length(); i++)
		{
			this.getOutputStream().write((byte) buffer.get(i));
		}
		this.getOutputStream().flush();
	}
	
	public void return404Response() throws IOException
	{
		this.getOutputStream().write("HTTP/1.1 404 Not Found\r\n".getBytes());
		this.getOutputStream().write("\r\n\r\n".getBytes());	
	}
	
	public String getSourcePort() {
		return sourcePort;
	}
	public void setSourcePort(String sourcePort) {
		this.sourcePort = sourcePort;
	}

	public void setRequestedFilename(String file)
	{
		this.requestedFilename = file;
	}
	public String getRequestedFilename() {
		return requestedFilename;
	}
	public boolean isFileFound()
	{
		return this.fileFound;
	}
	public void setFileFound(boolean fileFound) 
	{
		this.fileFound = fileFound;
	}
	
	public String getSourceHost() {
		return sourceHost;
	}

	public void setSourceHost(String sourceHost) {
		this.sourceHost = sourceHost;
	}


	public void setContentType(String type) 
	{
		this.contentType = type;
	}
	public String getContentType() {
		return contentType;
	}
}
